<link rel="stylesheet" type="text/css" href="<?php echo base_url() . 'public/css/dateinput.css'; ?>"/>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/bootstrap3-typeahead.min.js"></script>

<?php
$sidebar =
        '<ul id=\"admin-nav\">
    <li><a href=\"' . site_url("admin/home") . '\">Admin kodu</a></li>
    <li><a href=\"' . site_url("admin/competitions") . '\">Võistlused</a></li>
    <li><a href=\"' . site_url("admin/competitions/manual") . '\">Käsitsi sisestamine</a></li>
    <li><a href=\"' . site_url("admin/tables") . '\">Aegade ja punktide tabelid</a></li>
</ul>';

$sidebar = str_replace("\n", '\n', $sidebar);
?> 

<?php if (isset($error)) echo "<div class=\"alert alert-error\">$error</div>" ?>
<?php echo validation_errors(); ?>


<style>

    .content-row {
        margin-top: 5px;
        margin-bottom: 5px;
    }

    .time, #event_nr {
        width: 90px;
    }

    .typeahead {
        width: 270px;
    }

</style>
<script>
    var confirmOnPageExit = function (e) {
        // If we haven't been passed the event get the window.event
        e = e || window.event;

        var message = 'Täidetud ala ning tulemused lähevad lahkudes kaotsi.';

        // For IE6-8 and Firefox prior to version 4
        if (e) 
        {
            e.returnValue = message;
        }

        // For Chrome, Safari, IE8+ and Opera 12+
        return message;
    };
    
    //window.onbeforeunload = confirmOnPageExit;
    
    $(".page-header").html("<h1>Administraatori lehekülg</h1>");
    $(".sidebar").html("<?php echo $sidebar; ?>");
    
    $(document).ready(function () {
        
        athlete_labels = [];
        athlete_map = {};
        $.each(athlete_list, function(i, object) {
            athlete_map[object.label] = object;
            athlete_labels.push(object.label);
        });
        
        new_result_row();
        
    });

</script>

<?php
$tuk_id = 0;

foreach ($teams as /* @var $team Team */ $team) {
    $team_list[$team->getID()] = "$team->abbr";
    if ($tuk_id == 0 && $team->abbr == 'TUK') {
        $tuk_id = $team->getID();
    }
}

class Ath {

    var $id;
    var $label;

    function __construct($id, $label) {
        $this->id = $id;
        $this->label = $label;
    }

}

foreach ($athletes as /* @var $athlete Athlete */ $athlete) {
    $athlete_list[] = new Ath((int) $athlete->getID(), "$athlete->last_name $athlete->first_name {$athlete->getBirthYearLong()} T: $athlete->results");
}

$athlete_encode = json_encode($athlete_list);

$start_date = new DateTime($competition->getStartDate());
$start = $start_date->format("d M Y");
$end_date = new DateTime($competition->getEndDate());
$end = $end_date->format("d M Y");

$period = new DatePeriod($start_date, new DateInterval('P1D'), $end_date->modify('+1 day'));

foreach ($period as $date) {
    $date_period[$date->format('Y-m-d')] = $date->format('d M Y');
}
?>

<script type='text/javascript'>
    
    var result_count = 0;
    
    var header = '<div class="row content-row">\n<div class="col-md-12">\n<form class="form-inline" role="form">\n';
    var result_label = '<div class="form-group">\n<p class="form-control-static">Result #. </p>\n</div>';
    var athlete_list = <?php echo $athlete_encode; ?>;
    var team_form = '<div class="form-group">\n<?php echo str_replace("\n", "\\n", form_dropdown('team', $team_list, $tuk_id, 'id="result_team#" class="form-control"')); ?>\n</div>\n';
    var result_form = '<div class="form-group has-success">\n<input type="text" class="form-control time" id="result_result#" maxlength="8" placeholder="Result">\n</div>\n';
    var entry_form = '<div class="form-group">\n<input type="text" class="form-control time" id="result_entry#" maxlength="8" placeholder="Entry">\n</div>\n';
    var athlete_autocomplete = '<div class="form-group has-success">\n<input type="text" class="form-control typeahead" id="result_autocomplete#" data-provide="typeahead" data-items="5" placeholder="Nimi">\n</div>\n';
    var athlete_form = '<input type="hidden" id="result_athlete#" >';
    var exhibition_form = '<div class="form-group">\n<label>\n<input id="result_exh#" type="checkbox"> Exh.\n</label>\n</div>\n';
    var footer = '</form>\n</div>\n</div>\n';
    
    function generate_result_row(n) {
        var result_row = header + result_label + result_form + entry_form + team_form + athlete_autocomplete +athlete_form + exhibition_form + footer;
        return result_row.replace(/#/g, n);
    }
    
    function new_result_row() {
        result_count++;
        var n = result_count;
        
        $("#results_container").append(generate_result_row(result_count));
        $('#result_autocomplete'+n).typeahead({
            source: athlete_labels,
            updater: function(item) {
                $('#result_athlete'+n).val(athlete_map[item].id);
                return item;
            }
        }); 
        
        document.getElementById("result_result" + n).focus();
    }
    
    function save_results() {
        var results = new Array();
        for (var n = 1; n <= result_count; n++) {
            var result = result_from_fields(n);
            if (result != null) {
                results.push(result);
            }
        }
        
        if (results.length != 0) {
            var events_json = JSON.stringify(event_from_fields());
            var results_json = JSON.stringify(results);
            $('#events').val(events_json);
            $('#results').val(results_json);
            
            $("#upload_json").submit();
        } else {
            alert("Ühtegi tulemust pole sisetatud");
        }
        
    }
    
    function result_from_fields(n) {
        var seed = parse_time($("#result_entry"+n).val())
        var result_raw = $("#result_result"+n).val();
        var result_value = 0;
        if (result_raw.toUpperCase() != 'DQ') {
            result_value = parse_time(result_raw);
            result_value = isNaN(result_value) ? 0 : result_value;
        }
        seed = isNaN(seed) ? 0 : seed;
        var athlete_id = parseInt($("#result_athlete"+n).val());
        athlete_id = isNaN(athlete_id) ? 0 : athlete_id; 
        
        if (athlete_id == 0 || result_value == 0) {
            return null;
        } 
        
        var result = {
            "e_id": 1,
            "e_type": $("#event_type").val(),
            "athlete_id": athlete_id,
            "team_no": parseInt($("#result_team"+n).val()),
            "seed": seed,
            "result": result_value,
            "exhibition": $("#result_exh"+n).is(':checked') ? 1 : 0
        };
        return result;
    }
    
    function parse_time(raw) {
        if (raw == null) {
            return 0;
        }
        var tokens = raw.replace(",", ".").split(":", 2);
        if (tokens.length == 1) {
            return parseFloat(tokens[0]);
        } else if (tokens.length == 2) {
            return parseInt(tokens[0]) * 60 + parseFloat(tokens[1]);
        } else {
            return 0;
        }
    }
    
    function event_from_fields () {
        
        var nr = parseInt($("#event_nr").val());
        nr = isNaN(nr) ? 1 : nr;
        var event = [{
                "event_id": 1,
                "nr": nr,
                "distance": parseInt($("#event_distance").val()),
                "stroke": $("#event_stroke").val(),
                "relay": 0,
                "low_age": 0,
                "high_age": 109,
                "gender": $("#event_gender").val(),
                "type": $("#event_type").val(),
                "date": $("#event_date").val()
            }];
        return event;
        
    }
    
</script>

<div class="row content-row">
    <div class="col-md-10">
        <h3><?php echo "$competition->name ($competition->pool m)" ?></h3>
        <h4>
            <?php
            $daterange = $start == $end ? $start : "$start - $end";
            echo $daterange;
            ?>
        </h4>
    </div>
</div>

<div class="row content-row">
    <div class="col-md-10">
        <form class="form-inline" role="form">
            <div class="form-group">
                <p class="form-control-static">Event #</p>
            </div>
            <div class="form-group">
                <input type="number" class="form-control col-sm-2" id="event_nr" placeholder="#">
            </div>
            <div class="form-group">
                <select id="event_distance" class="form-control">
                    <option value="50">50m</option>
                    <option value="100">100m</option>
                    <option value="200">200m</option>
                    <option value="400">400m</option>
                    <option value="800">800m</option>
                    <option value="1500">1500m</option>
                    <option value="25">25m</option>
                </select>
            </div>
            <div class="form-group">
                <select id="event_stroke" class="form-control">
                    <option value="free">Freestyle</option>
                    <option value="back">Backstroke</option>
                    <option value="breast">Breaststroke</option>
                    <option value="fly">Butterfly</option>
                    <option value="medley">Medley</option>
                </select>
            </div>
            <div class="form-group">
                <select id="event_type" class="form-control">
                    <option value="F">Final</option>
                    <option value="P">Preliminary</option>
                    <option value="S">Semifinal</option>
                    <option value="SO">Swim-off</option>
                </select>
            </div>
            <div class="form-group">
                <select id="event_gender" class="form-control">
                    <option value="M">Men</option>
                    <option value="F">Women</option>
                </select>
            </div>

            <div class="form-group">
                <?php echo form_dropdown('date', $date_period, null, 'id="event_date" class="form-control"'); ?>
            </div>
        </form>
    </div>

</div>

<div class="row content-row">
    <div class="col-md-10">
        <p>Tulemus ja ülesandmine sisestada kujul 0:00,00 või 0:00.00 või 00,00 või 00.00 või DQ</p>
    </div>
</div>

<div class="row content-row">
    <div class="col-md-10" id="results_container">
    </div>
</div>

<div class="row content-row">
    <div class="col-sm-2">
        <button class="btn-default btn" onclick="new_result_row()">Lisa tulemus</button>
    </div>
</div>

<?php
echo form_open('files/manual_upload_json', 'id="upload_json" method="post"');
echo form_input(array('name' => 'competition_id', 'type' => 'hidden', 'id' => 'competition', 'value' => $competition->id));
echo form_input(array('name' => 'events', 'type' => 'hidden', 'id' => 'events'));
echo form_input(array('name' => 'results', 'type' => 'hidden', 'id' => 'results'));
echo form_close();
?>
<div class="row content-row">
    <div class="col-sm-2 col-md-offset-8">
        <button class="btn-default btn" onclick="save_results()">Salvesta tulemused</button>
    </div>
</div>
